﻿using ExitGames.Client.Photon;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;

public class PhotonManager : MonoBehaviour, IPhotonPeerListener
{
    public static PhotonManager Instance;

    /// <summary>
    /// 代表客户端
    /// </summary>
    private PhotonPeer peer;

    /// <summary>
    /// IP地址
    /// </summary>
    private string serverAddress = "192.168.1.4:5055";

    /// <summary>
    /// 名字
    /// </summary>
    private string applicationName = "Moba";

    /// <summary>
    /// 协议
    /// </summary>
    private ConnectionProtocol protocol = ConnectionProtocol.Udp;

    private bool isConnect = false;

    #region Photon接口

    public void DebugReturn(DebugLevel level, string message)
    {

    }

    public void OnEvent(EventData eventData)
    {

    }

    public void OnOperationResponse(OperationResponse operationResponse)
    {

    }

    /// <summary>
    /// 状态链接
    /// </summary>
    /// <param name="statusCode"></param>
    public void OnStatusChanged(StatusCode statusCode)
    {
        Debug.Log("====  " + statusCode);
        switch (statusCode)
        {
            case StatusCode.Connect:
                isConnect = true;
                break;
            case StatusCode.Disconnect:
                isConnect = false;
                break;
        }
    }

    #endregion

    private void Awake()
    {
        Instance = this;
        peer = new PhotonPeer(this, protocol);
        peer.Connect(serverAddress, applicationName);
    }

    private void Update()
    {
        //未连接
        if (!isConnect)
            peer.Connect(serverAddress, applicationName);
        peer.Service();
    }

    private void OnApplicaitonQuit()
    {
        //断开连接
        peer.Disconnect();
    }

    /// <summary>
    /// 向服务器发送请求
    /// </summary>
    /// <param name="opCode"></param>
    /// <param name="subCode"></param>
    /// <param name="paramters"></param>
    public void Request(byte code, byte subCode, params object[] paramters)
    {
        //创建参数字典
        Dictionary<byte, object> dict = new Dictionary<byte, object>();
        //指定子操作码
        dict[80] = subCode;
        //赋值参数
        for (int i = 0; i < paramters.Length; i++)
        {
            dict[(byte)i] = paramters[i];
        }
        //发送
        peer.OpCustom(code, dict, true);
    }
}
